package com.example.crm_system.service.impl;

import com.example.crm_system.entity.Customer;
import com.example.crm_system.entity.Params;
import com.example.crm_system.exception.MyOwnException;
import com.example.crm_system.mapper.CustomerMapper;
import com.example.crm_system.service.CustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerMapper customerMapper;

    @Override
    public void insert(Customer customer) {
        if (customer.getCname() == null || customer.getCname().isEmpty()) {
            throw new MyOwnException("用户名不能为空");
        }
        Customer cus = customerMapper.selectByPhone(customer.getPhone());
        if (cus != null) {
            throw new MyOwnException("该手机号码已存在");
        }
        customerMapper.insert(customer);
    }

    @Override
    public void update(Customer customer) {
        customerMapper.update(customer);
    }

    @Override
    public void delete(Integer cno) {
        customerMapper.delete(cno);
    }

    @Override
    public List<Customer> selectAll() {
        return customerMapper.selectAll();
    }

    @Override
    public List<Customer> selectByCno(Integer cno) { return customerMapper.selectByCno(cno); }

    @Override
    public PageInfo<Customer> searchCustomer(Params params) {
        // 开启分页查询功能
        if (params != null && params.getPageNum() != null && params.getPageSize() != null) {
            // 开启分页查询功能
            PageHelper.startPage(params.getPageNum(), params.getPageSize());
        }
        // 接下来的查询会自动按照当前开启的分页设置来查询
        List<Customer> list = customerMapper.searchCustomer(params);
        return PageInfo.of(list);
    }

    @Override
    public List<Customer> findAll() {
        return customerMapper.selectAll();
    }
}
